package generateConnections;

import java.util.ArrayList;

import logging.Logger;

import exception.NoConnectionPossibleException;

import networkInterface.NetworkInterfaceBase;

import object.Node;
import util.NodeUtil;

public class GenerateDynamicNetwork extends GenerateConnectionBase {

	@Override
	public void genConnections(ArrayList<Node> nodes, Node node) {
		
		// get a list of available connections
		for( NetworkInterfaceBase root : node.getInterfaces() )
		{
			// gather nodes we could possibly connect to
			ArrayList<NetworkInterfaceBase> possible = root.getPossiblyConnectableInterfaces(nodes);
			if( possible.isEmpty() )
			{
				return;
			}
			
			int index = 0;
			while( root.hasConnectionsAvailible() && index < possible.size() )
			{
				NetworkInterfaceBase ConnectToMe = NodeUtil.removeSingleConnection(possible.get(index).getNode(), root);
				if( ConnectToMe != null )
				{
					try {
						root.addConnection( ConnectToMe );
					} catch (IllegalStateException e) {
						Logger.getInstance().log(Logger.WARNING, "GenerateDynamicNetwork: Reached an unpleasant state while attempting to create a new connection");
					} catch (NoConnectionPossibleException e) {
						Logger.getInstance().log(Logger.WARNING, "GenerateDynamicNetwork: Could not create a connection");
					}
				}
				index++;
			}
			
			
		}
		
		
		// Loop at interface to gather connections
		// Look for possible connectable interfaces
		// gather network information for possible interfaces
		// find the largest possible network to join
		// ask that node for an open interface
		// if an interface is returned, connect to that interface
		
		// other things to be aware of
		// should use all of the connections available for a node
		// should disperse them randomly to open nodes

	}

}
